Skip to content

[Fix #519] Fix false positives for Performance/StringInclude when match result is used - #557

Open
kshtzkr wants to merge 1 commit into
rubocop:masterfrom
kshtzkr:fix_string_include_with_chained_match
Open

kshtzkr wants to merge 1 commit into
rubocop:masterfrom
kshtzkr:fix_string_include_with_chained_match

Conversation

@kshtzkr

@kshtzkr kshtzkr commented Nov 8, 2026

Copy link
Copy Markdown

match returns MatchData or nil, so code like this uses the match value itself:

items.map { it.match(/A/)&.to_s } # => ["A", nil]

The cop suggested include?, which returns a boolean and changes the result. Following the maintainer's suggestion on the issue, the cop now skips match when a method is called on its result (.to_s, &.to_s, [0]). An unchained match is still flagged.

To keep on_send within Metrics/CyclomaticComplexity, the existing !~ check moved into a negation? helper. Behaviour is unchanged.

Fixes #519.


Before submitting the PR make sure the following are checked:

  • The PR relates to only one subject with a clear title and description in grammatically correct, complete sentences.
  • Wrote good commit messages.
  • Commit message starts with [Fix #issue-number] (if the related issue exists).
  • Feature branch is up-to-date with master (if not - rebase it).
  • Squashed related commits together.
  • Added tests.
  • Ran bundle exec rake default. It executes all tests and runs RuboCop on its own code.
  • Added an entry (file) to the changelog folder named {change_type}_{change_description}.md if the new code introduces user-observable changes. See changelog entry format for details.

… when `match` result is used

`match` returns `MatchData` or `nil`, so code such as `str.match(/abc/)&.to_s`
uses the match itself, not a boolean. Replacing it with `include?` changes
the result. Skip `match` when a method is called on its result.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Performance/StringInclude doesn't consider assignment context

1 participant